/**
 * 
 */
package com.etc.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import com.etc.common.util.StringUtil;
import com.etc.token.CaptchaAuthenticationToken;
import com.google.code.kaptcha.Constants;

/**
 * @author Administrator
 *
 */
public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter {
	
	public static final String DEFAULT_CAPTCHA_PARAM = "kaptcha";
	
	private String captchaParam=DEFAULT_CAPTCHA_PARAM;

    public String getCaptchaParam() {
        return captchaParam;
    }
    
    

    public void setCaptchaParam(String captchaParam) {
		this.captchaParam = captchaParam;
	}



	protected String getCaptcha(ServletRequest request) {
        return WebUtils.getCleanParam(request, getCaptchaParam());
    }

    @Override
    protected AuthenticationToken createToken(ServletRequest request,
            ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        String captcha = getCaptcha(request);
        String remeberMe=request.getParameter("remeberMe");
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
        return new CaptchaAuthenticationToken(username, password, rememberMe,
                host, captcha);
    }

   // 验证码校验
    protected boolean doCaptchaValidate(ServletRequest request,ServletResponse response) {
    	HttpServletRequest httpServletRequest=WebUtils.toHttp(request);
    	 CaptchaAuthenticationToken token =(CaptchaAuthenticationToken)createToken(request, response);
        String captcha = (String) httpServletRequest.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

        if (StringUtil.isEmpty(token.getKaptcha()) || !token.getKaptcha().equalsIgnoreCase(captcha)) {
           return false;
        }
        return true;
    }



	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) {
		 String remeberMe=request.getParameter("tsuName");
		return doCaptchaValidate(request, response);
	}

}
